/* eslint-disable */

function removeScript(url, callback) {
    let old_script = document.getElementById(url);
    if (old_script) {
        if (old_script.ready == true) {
            // console.log("Already load:" + url);
            callback();
            return;
        }
        else {
            document.body.removeChild(old_script);
            // console.log("Remove an old script that not ready:" + url);
        }
    }
}

function LoadScript(url, callback) {
    removeScript(url, callback);
    return new Promise((resolve, reject) => {
        let script = null;
        if (url.endsWith('.css')) {
            script = document.createElement("link");
            script.id = url;
            script.type = 'text/css';
            script.rel = 'stylesheet';
            script.href = url;
        } else {
            script = document.createElement('script');
            script.id = url;
            script.src = url;
            script.type = 'text/javascript';
        }
        script.onload = script.onreadystatechange = function () {
            if (script.ready) {
                return false;
            }
            if (!script.readyState || script.readyState == "loaded" || script.readyState == 'complete') {
                // console.log("load:" + url);
                script.ready = true;
                callback();
                resolve(url)
            }
        };
        document.body.appendChild(script);
    })

}

async function LoadScripts(scripts, callback) {
    var ok = 0;
    for (var i = 0; i < scripts.length; i++) {
        await LoadScript(scripts[i], function () {
            ok++;
            if (ok == scripts.length) {
                callback();
            }
        })
    }
}


export default LoadScripts;